<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)</title>
</head>

<body>

    <input type="text" id="msg"><input type="button" onclick="sendMsg()" value="发送">
    <form action="">
        用户名：<input type="text" name="username" id="username"><br> 密码：
        <input type="password" name="password" id="password"><br>
        <input type="button" value="登录" onclick="login()">
        <input type="button" value="绑定" onclick="bind()">
    </form>

    <script type="text/javascript">
        // 打开一个 web socket
        var ws = new WebSocket("ws://localhost:3001");

        ws.onopen = function () {
            // Web Socket 已连接上，使用 send() 方法发送数据
            var resuest = {
                RequestType: 1
            }
            ws.send(JSON.stringify(resuest));
        };

        ws.onmessage = function (evt) {
            var received_msg = evt.data;
            console.log(received_msg);
        };

        ws.onclose = function () {
            // 关闭 websocket
            console.log("连接已关闭...");
        };

        function login() {
            var user = {
                KeyId: document.getElementById("username").value,
                Password: document.getElementById("password").value
            }
            var WsRequest = {
                RequestType: 0,
                RequestParam: JSON.stringify(user)
            }
            ws.send(JSON.stringify(WsRequest));
        }

        function bind() {
            var WsRequest = {
                RequestType: 2,
                RequestParam: document.getElementById("username").value
            }
            ws.send(JSON.stringify(WsRequest));
        }


        function sendMsg() {
            var value = document.getElementById("msg").value;
            ws.send(value);
        }
    </script>
</body>

</html>